package edu.hawaii.duedates.libraries;

import java.util.Calendar;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

import edu.hawaii.duedates.Library;

/**
 * UHMLibrary.class
 * UHMLibrary enables the communication between our DueDates interface and the 
 * physical UHM Library System. It is also responsible for retrieving the 
 * required information, given the parameters passed by DueDates.
 *  
 * @author Anthony Du, Vincent Leung 
 *
 */
public class UHMLibrary extends Library {
  
  /**
   * Constructor for creating a library and setting user's credentials.
   * @param n String of library's name.
   * @param id String of user's id.
   * @param key String of user's key.
   */
  public UHMLibrary(String n, String id, String key) {
    super(n, id, key);
  }
  
  /**
   * Attempts to login to UH Manoa Library system.  
   * @param id The UH user ID. 
   * @param lastName  The UH user's last name. 
   * @return The WebConversation instance after successful login. 
   * @throws Exception If login was not successful with these credentials. 
   */
  @Override
  public WebConversation logIntoLibrary(String id, String lastName) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", id);
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      System.out.println("Sorry, Login unsuccessful.");
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books. 
   * @return A String containing information about their books.
   * @throws Exception If problems occur parsing the site pages. 
   */
  @Override
  public String getLibInfo() throws Exception {
    String uhSiteNoItemString = "You have no items checked out.";
    try {
      WebConversation conversation = this.logIntoLibrary(getId(), getKey());    
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];  
      if (uhSiteNoItemString.equals(form.getText())) {
        return "No items checked out";
      }
      else {
        String bookInfo = "";
        String bookDate = "";
        int month = 0;
        int day = 0;
        int year = 0;
        String delims = "[-]";
        String [] token;
        Calendar calendar = Calendar.getInstance();
        int numFormTables = response.getTables().length;
        StringBuffer buf = new StringBuffer(99);
        for (int i = 0; i < numFormTables; i++) {
          WebTable table = response.getTables()[i];
          int rowCounter = table.getRowCount();
          for (int j = 1; j < rowCounter; j++) {
            if (table.getCellAsText(j, 2).equals("Book")) {
              buf.append("title: " + table.getCellAsText(j, 1) + "\ntype: " 
              + table.getCellAsText(j, 2) + "\nstatus: " + table.getCellAsText(j, 3) + "\n");
              //trying simpledateformat
              //month - 1 because it starts from 0.
              //year + 2000 because table only provides last two digits.
              bookDate = table.getCellAsText(j, 3);
              bookDate = bookDate.substring(17);
              token = bookDate.split(delims);
              month = Integer.parseInt(token[0]) - 1;
              day = Integer.parseInt(token[1]);
              year = Integer.parseInt(token[2]) + 2000;
              calendar.set(year, month, day, 0, 0, 0);
              System.out.println(calendar.getTime());
            }
//            else{
//              System.out.println("No books are checked out.");
//            }
          }
        }
        bookInfo = buf.toString();
        return "At least one book is checked out: \n" + bookInfo;
        
      }
    }
    catch (Exception e) {
      System.out.println("No books are checked out.");
      throw new Exception("Error getting UH Book info", e);
    }

  }
}